package com.bocloud.cmp.driver.providers.jd;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.providers.ImageDriver;
import com.bocloud.cmp.model.ImageModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;
import com.jcloud.cap.client.ClientConfig;
import com.jcloud.cap.client.IClient;
import com.jcloud.cap.client.JCloudClient;
import com.jcloud.cap.client.builder.v1.QueryImageDetailRequestBuilder;
import com.jcloud.cap.client.builder.v1.QueryImagesRequestBuilder;
import com.jcloud.cap.client.exception.ClientException;
import com.jcloud.cap.client.exception.ServerException;
import com.jcloud.cap.client.http.HttpConfig;
import com.jcloud.cap.data.model.v1.QueryImageDetailResponse;
import com.jcloud.cap.data.model.v1.QueryImagesResponse;
import com.jcloud.cap.data.model.v1.QueryImagesResponse.Image;

public class JdImageDriver extends JdDriver implements ImageDriver {

	private static Logger logger = LoggerFactory.getLogger(JdImageDriver.class);
	private IClient client;

	/**
	 * @param accessKey
	 * @param secretKey
	 * @param endpoint
	 */
	public JdImageDriver(String accessKey, String secretKey, String endpoint, String region) {
		super(accessKey, secretKey, endpoint, region);
		ClientConfig config = new ClientConfig();
		HttpConfig httpConfig = new HttpConfig();
		// 调用地址
		httpConfig.setEndpoint(endpoint);
		httpConfig.setReadTimeout(20000);
		httpConfig.setConnectTimeout(20000);
		config.setHttpConfig(httpConfig);
		config.setCredential(this.getCredential().getCapCredential());
		client = new JCloudClient(config);
	}

	@Override
	public BsmResult list() {
		QueryImagesRequestBuilder builder = QueryImagesRequestBuilder.create();
		this.init(builder, "image", "queryImages", this.getRegion());
		try {
			QueryImagesResponse response = client.send(builder.type("public").build());
			List<Image> images = response.getImages();
			List<ImageModel> models = Lists.newArrayList();
			if (null != images && !images.isEmpty()) {
				QueryImageDetailRequestBuilder detailBuilder = QueryImageDetailRequestBuilder.create();
				this.init(detailBuilder, "image", "queryImageDetail", this.getRegion());
				for (Image image : images) {
					ImageModel model = convert(image);
					QueryImageDetailResponse detailResponse = client
							.send(detailBuilder.imageId(image.getImageId()).build());
					if (null != detailResponse) {
						model.setRemark(detailResponse.getDescription());
						model.setKernelVersion(detailResponse.getKernelVersion());
						model.setOsType(detailResponse.getType());
						BigDecimal decimal = new BigDecimal(detailResponse.getSize());
						double size = decimal.divide(new BigDecimal(1024 * 1024 * 1024), 2, RoundingMode.HALF_UP)
								.doubleValue();
						model.setSize(size);
					}
					models.add(model);
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException | ServerException e) {
			logger.error("List image [{}] exception!", e);
			return new BsmResult(false, "List image failed");
		}
	}

	@Override
	public BsmResult detail(String imageId) {
		QueryImagesRequestBuilder builder = QueryImagesRequestBuilder.create();
		this.init(builder, "image", "queryImages", this.getRegion());
		try {
			QueryImagesResponse response = client.send(builder.type("public").build());
			List<Image> images = response.getImages();
			ImageModel model = null;
			if (null != images && !images.isEmpty()) {
				for (Image image : images) {
					if (image.getImageId().equals(imageId)) {
						QueryImageDetailRequestBuilder detailBuilder = QueryImageDetailRequestBuilder.create();
						this.init(detailBuilder, "image", "queryImageDetail", this.getRegion());
						model = convert(image);
						QueryImageDetailResponse detailResponse = client
								.send(detailBuilder.imageId(image.getImageId()).build());
						if (null != detailResponse) {
							model.setRemark(detailResponse.getDescription());
							model.setKernelVersion(detailResponse.getKernelVersion());
							model.setOsType(detailResponse.getType());
							BigDecimal decimal = new BigDecimal(detailResponse.getSize());
							double size = decimal.divide(new BigDecimal(1024 * 1024 * 1024), 2, RoundingMode.HALF_UP)
									.doubleValue();
							model.setSize(size);
						}
					}
				}
			}
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query image [{}] exception!", e);
			return new BsmResult(false, "Query image failed");
		}
	}

	private ImageModel convert(Image image) {
		if (null == image) {
			return null;
		}
		return new ImageModel(image.getImageName(), image.getImageStatus(), null, image.getCreateTime(), image.getOs(),
				image.getSystemVersion(), null, image.getImageId(), image.getArchitectureVersion(), null, null,
				image.getBase(), image.getBaseShow(), null);
	}

	@Override
	public BsmResult remove(String imageId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult modify(ImageModel image) {
		// TODO Auto-generated method stub
		return null;
	}
}
